package com.appspot.moviesessions.infrastructure.scraper;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;

import org.apache.commons.io.IOUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

public class URLFetchServiceImpl implements URLFetchService, HttpClientFactory {

	public URLFetchServiceImpl() {
		Properties props = System.getProperties();
//		props.put("http.proxyHost", "localhost");
//		props.put("http.proxyPort", "3128");
	}

	@Override
	public byte[] fetch(URL url) {

		ByteArrayOutputStream ostream = new ByteArrayOutputStream();
		try {

			IOUtils.copy(url.openStream(), ostream);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return ostream.toByteArray();
	}

	@Override
	public HTTPResponse fetch(HTTPRequest with) {
		com.google.appengine.api.urlfetch.URLFetchService service = URLFetchServiceFactory
		        .getURLFetchService();
		with.getFetchOptions().setDeadline(59d);
		try {
			return service.fetch(with);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public WebDriver create() {
		DesiredCapabilities firefox = DesiredCapabilities.firefox();
		firefox.setJavascriptEnabled(true);
		HtmlUnitDriver driver = new HtmlUnitDriver(firefox);

		return driver;
	}

}
